package com.markix.security.oauth2login;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author markix
 * @date 2022/9/2 17:13
 */
@Slf4j
public class OAuth2LoginAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 1.当前有登录用户，跳主页，提示绑定失败（绑定操作）
        // 2.当前无登录用户，跳登录页面（三方登录操作）

        log.warn("三方授权失败", exception);
        if(TempAuthContext.notEmpty()){
            // 还原已登录用户的认证信息
            SecurityContextHolder.getContext().setAuthentication(TempAuthContext.get());
            // 绑定失败
            getRedirectStrategy().sendRedirect(request, response, WebAttributes.bindFailure);
            return;
        }
        // 三方登录失败
        getRedirectStrategy().sendRedirect(request, response, WebAttributes.oauth2LoginError);
    }

}
